#include "delay_plan_thread.h"

#include "pfunc.h"
#include "Log.h"

#include "business_def.h"
#ifdef WIN32
#define usleep(x) Sleep(x)
#endif

DelayPlanThread::DelayPlanThread(void) 
	: running(true)
	, ptr_bdef(BusinessDef::getInstance())
	, socket_write_queue(QueueDataSingle<DataToGather>::getInstance())
{

}
DelayPlanThread::~DelayPlanThread(void)
{
	running = false;
}
void* DelayPlanThread::run()
{
	unsigned long _usec = 0;
	while (running)
	{
		try {
			_usec = static_cast<unsigned long>(pyfree::getClockTime());
			delay_plan_list_Mutex.Lock();
			std::list<DataToGather>::iterator it = delay_plan_list.begin();
			while (it != delay_plan_list.end())
			{
				if (it->sleep < _usec) 
				{
					//printf("sleep(%ld),usec(%ld)\n", it->sleep, _usec);
					if (it->virtualP) 
					{
						PValueRet pret(it->val);
						ptr_bdef->setHValue(it->ipInt, static_cast<unsigned int>(it->pID), pret,true);
						CLogger::createInstance()->Log(MsgInfo
							, "TaskID[%lu] and down_node[1-2] setPValue(virtual-point) from delay exec"
							",time(%s),devID(%ld),pID(%ld),val(%.3f)"
							",ditect set val to virtual ponit control"
							, it->taskID, pyfree::getCurrentTime().c_str()
							, it->ipInt, it->pID, pret.val_actual);
					}
					else 
					{
						socket_write_queue->add(*it);
						CLogger::createInstance()->Log(MsgInfo
							, "TaskID[%lu] and down_node[1-2] setPValue from plan for delay exec"
							",cmd(%s),time(%s),ip(%ld),pID(%d),pType(%d),val(%.3f)"
							, it->taskID, it->desc.c_str(), pyfree::getCurrentTime().c_str()
							, it->ipInt, it->pID, static_cast<int>(it->pType), it->val);
					}
					it = delay_plan_list.erase(it);
					continue;
				}
				it++;
			}
			delay_plan_list_Mutex.Unlock();
		}
		catch (const std::exception& e)
		{
			CLogger::createInstance()->Log(MsgError,
				"DelayPlanThread running have error[%s]. [%s %s %d]"
				, e.what()
				, __FILE__, __FUNCTION__, __LINE__);
		}
		catch (...) 
		{
			Print_WARN("error for get sleep item WDS and add to ReceiveData \n");
		}
		usleep(1);
	}
	return 0;
}

void DelayPlanThread::addDelayExec(DataToGather wd)
{
	delay_plan_list_Mutex.Lock();
	delay_plan_list.push_back(wd);
	delay_plan_list_Mutex.Unlock();
};
